package com.xiaorun.portal.spider.processer;

import com.xiaorun.portal.constant.WebConst;
import com.xiaorun.portal.modal.Vo.News;
import com.xiaorun.portal.modal.Vo.NewsAttach;
import com.xiaorun.portal.modal.Vo.Notice;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class NoticePageProcesser implements PageProcessor {

    //列表链接
    public static final String URL_LIST_TDGG = "http://www.sz68.com/b/tdgg\\?s=\\d+";
    public static final String URL_LIST_ZCFG = "http://www.sz68.com/b/zcfg\\?s=\\d+";

    //详情页链接
    public static final String URL_DETAIL = "http://www.sz68.com/b/";


    //    部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
//    private Site site = Site.me().setDomain("www.sz68.com").setRetryTimes(3).setSleepTime(1000).setTimeOut(600000).addHeader("Accept-Encoding", "/").setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36");
    private Site site = Site.me().setDomain("www.sz68.com");

    @Override
    public Site getSite() {
        return site;
    }

    public Date getDateFromStr(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd hh:mm");
        Pattern pattern = Pattern.compile("[0-9]{2}[-][0-9]{1,2}[-][0-9]{1,2}[ ][0-9]{1,2}[:][0-9]{1,2}");
        Matcher matcher = pattern.matcher(str);
        try {
            while (matcher.find ()) {
                return sdf.parse(matcher.group());
            }
        } catch (Exception e) {
            log.error("时间转换异常", e);
        }
        return null;
    }

    @Override
    public void process(Page page) {

        if (page.getUrl().regex(URL_LIST_TDGG).match()) {
            //加入满足条件的链接
            List<String> links = new ArrayList<>(20);
            links.addAll(page.getHtml().xpath("/html/body/main/div/div[2]/div/div[1]/table/tbody/tr/td[1]/strong/a/@href").all());
            page.addTargetRequests(links);
            page.setSkip(true);
        } else if (page.getUrl().regex(URL_DETAIL).match()) {
            Html html = page.getHtml();

            String dateStr =html.xpath("/html/body/main/div/div[2]/div/div[1]/table/tbody/tr[1]/td[1]/text()").toString().replace("公告", "") ;
            dateStr = StringUtils.strip(dateStr);
            Date publishTime = getDateFromStr(dateStr);
            String title = html.xpath("/html/body/main/div/div[1]/h5/text()").toString();
            if (StringUtils.isBlank(title)) {
                page.setSkip(true);
            }
            String content = html.xpath("/html/body/main/div/div[2]/div/div[1]/table/tbody/tr[2]/td[1]/div[2]/html()").toString().trim();
            String source = page.getUrl().toString();

            Notice notice = new Notice();
            notice.setTitle(title);
            notice.setContent(content);
            notice.setPublishTime(publishTime);
            notice.setType(WebConst.TDGG);
            notice.setSource(source);
            page.putField("notice", notice);

        }
    }

}
